const sass = require('sass')
const postcss = require('postcss')
const fs = require('fs')
const cleanCSS = require('clean-css')
const _ = require('lodash')


const removeSelectors = postcss.plugin('postcss-removeSelectors', function(opts) {
    function filterSelectors(selectors) {
        const rv = [];
        return _.filter(selectors, (selector) => {
            if (_.endsWith(selector, ':hover')) {
                return false
            }

            return true
        });
    }

    return function (root, result) {
        root.walkRules(rule => {
            const selectors = filterSelectors(rule.selectors)
            if (selectors.length) {
                rule.selectors = selectors
            } else {
                rule.remove();
            }
        })
    }
})


const responsive = postcss.plugin('postcss-responsive', function (opts) {
    const screens = (opts || {}).screens;

    function makeMediaQuery(nodes, prefix, query) {
        const media = postcss.atRule({
            name: 'media',
            params: 'only screen and ' + query,
            nodes: [],
        })
        nodes.forEach(node => {
            let newNode = node.clone();
            newNode.selectors = _.map(newNode.selectors, (selector) => {
                return prefixSelector(prefix, selector)
            })
            media.nodes.push(newNode)
        })

        return media;
    }

    function prefixSelector(prefix, selector) {
        return selector.replace(/\./, `.${prefix}-`)
    }

    function makeResponsive(nodes) {
        const result = [].concat(nodes);
        if (_.indexOf(screens, 'sm') >= 0) {
            result.push(makeMediaQuery(nodes, 'sm', '(max-width: 767px)'))
        }
        if (_.indexOf(screens, 'md') >= 0) {
            result.push(makeMediaQuery(nodes, 'md', '(min-width: 768px) and (max-width: 991px)'))
        }
        if (_.indexOf(screens, 'lg') >= 0) {
            result.push(makeMediaQuery(nodes, 'lg', '(min-width: 992px)'))
        }
        return result
    }

    return function (root, result) {
        let rootNodes = [];

        root.nodes.forEach(node => {
            if (node.type == 'atrule' && node.name == 'responsive') {
                rootNodes = rootNodes.concat(...makeResponsive(node.nodes))
            } else {
                rootNodes.push(node)
            }
        })

        root.nodes = rootNodes
    };
});


sass.render({
    file: 'style.scss',
}, (err, result) => {
    if (err) {
        console.error(err);
        return
    }

    if (!fs.existsSync('dist'))
        fs.mkdirSync('dist')
    if (!fs.existsSync('dist/css'))
        fs.mkdirSync('dist/css')

    var errHandler = (msg) => {
        return (err) => {
            if (err) {
                console.log(msg, err)
            }
        }
    }

    const styleDist = 'dist/css/venus.css'
    const minStyleDist = 'dist/css/venus.min.css'
    postcss([responsive({screens: ['sm']})]).process(result.css.toString()).then(result => {
        fs.writeFile(styleDist, result.css, errHandler(`write ${styleDist} error.`))

        const clean = new cleanCSS({level: {2: {
            all: true,
        }}})
        clean.minify(result.css, (err, output) => {
            errHandler('minify error.')(err)
            if (!err) {
                fs.writeFile(minStyleDist, output.styles, errHandler(`write ${minStyleDist} error.`))
            }
        })
    })
})
